package com.xoa.service.dutypoliceusers.impl;

import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.dutypoliceusers.DutyPoliceUsersMapper;
import com.xoa.dev.qywx.service.QywxService;
import com.xoa.model.budget.BudgetItem;
import com.xoa.model.common.SysCode;
import com.xoa.model.dutypoliceusers.DutyPoliceUsers;
import com.xoa.model.institution.InstitutionContentWithBLOBs;
import com.xoa.model.sms.SmsBody;
import com.xoa.model.users.Users;
import com.xoa.service.dutypoliceusers.DutyPoliceUsersService;
import com.xoa.service.sms.SmsService;
import com.xoa.service.users.UsersService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.DateFormat;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.dataSource.ContextHolder;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class DutyPoliceUsersServiceImpl implements DutyPoliceUsersService {

    @Autowired
    private DutyPoliceUsersMapper dutyPoliceUsersMapper;

    @Autowired
    private UsersService usersService;

    @Autowired
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Resource
    private SysCodeMapper sysCodeMapper;

    @Resource
    private SmsService smsService;

    @Resource
    private QywxService qywxService;

    /**
     * @Author 廉立深
     * @Description 条件查询
     * @Date 16:35 2020/5/21
     * @Param [request, dutyPoliceUsers]
     * @return com.xoa.util.ToJson
     **/
    @Override
    public ToJson findDutyPoliceWhere(HttpServletRequest request, DutyPoliceUsers dutyPoliceUsers,Integer page,Integer limit) {
        ToJson toJson=new ToJson(1,"err");
        try {
            Map map =new HashMap();

            //时间范围
            map.put("dutyDate",dutyPoliceUsers.getDutyDate());
            map.put("dutyDateEnd",dutyPoliceUsers.getDutyDateEnd());

            List<DutyPoliceUsers> dutyPoliceUsers1 = dutyPoliceUsersMapper.findDutyPoliceWhere(map);
            for (DutyPoliceUsers dutyPoliceUsers2:dutyPoliceUsers1) {

                //返回星期 getWeekOfDate
                dutyPoliceUsers2.setDutyweek(DateFormat.getWeekOfDate(dutyPoliceUsers2.getDutyDate()));

                //局带班
                if (!StringUtils.checkNull(dutyPoliceUsers2.getBtreeUsers())){
                    dutyPoliceUsers2.setBtreeUsersName(usersService.getUserNameById(dutyPoliceUsers2.getBtreeUsers()));
                }
                //据值班
                if (!StringUtils.checkNull(dutyPoliceUsers2.getBdutyUsers())){
                    dutyPoliceUsers2.setBdutyUsersName(usersService.getUserNameById(dutyPoliceUsers2.getBdutyUsers()));
                }
                //总站带班
                if (!StringUtils.checkNull(dutyPoliceUsers2.getTtreeUsers())){
                    dutyPoliceUsers2.setTtreeUsersName(usersService.getUserNameById(dutyPoliceUsers2.getTtreeUsers()));
                }
                //总站值班
                if (!StringUtils.checkNull(dutyPoliceUsers2.getTdutyUsers())){
                    dutyPoliceUsers2.setTdutyUsersName(usersService.getUserNameById(dutyPoliceUsers2.getTdutyUsers()));
                }
                //操作员
                if (!StringUtils.checkNull(dutyPoliceUsers2.getOperatingUsers())){
                    dutyPoliceUsers2.setOperatingUsers(usersService.getUserNameById(dutyPoliceUsers2.getOperatingUsers()));
                }
                //总站备勤
                if (!StringUtils.checkNull(dutyPoliceUsers2.getPreparationUsers())){
                    dutyPoliceUsers2.setPreparationUsersName(usersService.getUserNameById(dutyPoliceUsers2.getPreparationUsers()));
                }
                //中心值班长
                if (!StringUtils.checkNull(dutyPoliceUsers2.getCbigUsers())){
                    dutyPoliceUsers2.setCbigUsersName(usersService.getUserNameById(dutyPoliceUsers2.getCbigUsers()));
                }
                //中心值班员
                if (!StringUtils.checkNull(dutyPoliceUsers2.getCpersonUsers())){
                    dutyPoliceUsers2.setCpersonUsersName(usersService.getUserNameById(dutyPoliceUsers2.getCpersonUsers()));
                }
            }
            toJson.setObj(dutyPoliceUsers1);
            toJson.setMsg("ok");
            toJson.setFlag(0);
        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    /**
     * @Author 廉立深
     * @Description 根据ID查询
     * @Date 16:35 2020/5/21
     * @Param [request, dutyPoliceUsers]
     * @return com.xoa.util.ToJson
     **/
    @Override
    public ToJson findDutyPoliceById(HttpServletRequest request, DutyPoliceUsers dutyPoliceUsers) {
        ToJson toJson=new ToJson(1,"err");
        try {
            DutyPoliceUsers dutyPoliceUsers1 = dutyPoliceUsersMapper.selectByPrimaryKey(dutyPoliceUsers.getDutyId());
            if (dutyPoliceUsers1!=null){

                //返回星期 getWeekOfDate
                dutyPoliceUsers1.setDutyweek(DateFormat.getWeekOfDate(dutyPoliceUsers1.getDutyDate()));

                //局带班
                if (!StringUtils.checkNull(dutyPoliceUsers1.getBtreeUsers())){
                    dutyPoliceUsers1.setBtreeUsersName(usersService.getUserNameById(dutyPoliceUsers1.getBtreeUsers()));
                }
                //据值班
                if (!StringUtils.checkNull(dutyPoliceUsers1.getBdutyUsers())){
                    dutyPoliceUsers1.setBdutyUsersName(usersService.getUserNameById(dutyPoliceUsers1.getBdutyUsers()));
                }
                //总站带班
                if (!StringUtils.checkNull(dutyPoliceUsers1.getTtreeUsers())){
                    dutyPoliceUsers1.setTtreeUsersName(usersService.getUserNameById(dutyPoliceUsers1.getTtreeUsers()));
                }
                //总站值班
                if (!StringUtils.checkNull(dutyPoliceUsers1.getTdutyUsers())){
                    dutyPoliceUsers1.setTdutyUsersName(usersService.getUserNameById(dutyPoliceUsers1.getTdutyUsers()));
                }
                //操作员
                if (!StringUtils.checkNull(dutyPoliceUsers1.getOperatingUsers())){
                    dutyPoliceUsers1.setOperatingUsers(usersService.getUserNameById(dutyPoliceUsers1.getOperatingUsers()));
                }
                //总站备勤
                if (!StringUtils.checkNull(dutyPoliceUsers1.getPreparationUsers())){
                    dutyPoliceUsers1.setPreparationUsersName(usersService.getUserNameById(dutyPoliceUsers1.getPreparationUsers()));
                }
                //中心值班长
                if (!StringUtils.checkNull(dutyPoliceUsers1.getCbigUsers())){
                    dutyPoliceUsers1.setCbigUsersName(usersService.getUserNameById(dutyPoliceUsers1.getCbigUsers()));
                }
                //中心值班员
                if (!StringUtils.checkNull(dutyPoliceUsers1.getCpersonUsers())){
                    dutyPoliceUsers1.setCpersonUsersName(usersService.getUserNameById(dutyPoliceUsers1.getCpersonUsers()));
                }

                toJson.setObject(dutyPoliceUsers1);
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }

        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    /**
     * @Author 廉立深
     * @Description 编辑和新增
     * @Date 16:35 2020/5/21
     * @Param [request, dutyPoliceUsers]
     * @return com.xoa.util.ToJson
     **/
    @Override
    public ToJson editOrInsertDuty(HttpServletRequest request, DutyPoliceUsers dutyPoliceUsers) {
        ToJson toJson=new ToJson(1,"err");
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
        try {
            int i=0;
            if (dutyPoliceUsers.getDutyId()!=null){
                i=dutyPoliceUsersMapper.updateByPrimaryKeySelective(dutyPoliceUsers);
            }else{
                dutyPoliceUsers.setCreateUser(users.getUserId());
                dutyPoliceUsers.setCreateTime(new Date());
                i=dutyPoliceUsersMapper.insertSelective(dutyPoliceUsers);
            }
            if (i>0){
                toJson.setMsg("ok");
                toJson.setFlag(0);
                StringBuffer stringBuffer=new StringBuffer();
                //局带班
                if (!StringUtils.checkNull(dutyPoliceUsers.getBtreeUsers())){
                    stringBuffer.append(dutyPoliceUsers.getBtreeUsers());
                }
                //据值班
                if (!StringUtils.checkNull(dutyPoliceUsers.getBdutyUsers())){
                    stringBuffer.append(dutyPoliceUsers.getBdutyUsers());
                }
                //总站带班
                if (!StringUtils.checkNull(dutyPoliceUsers.getTtreeUsers())){
                    stringBuffer.append(dutyPoliceUsers.getTtreeUsers());
                }
                //总站值班
                if (!StringUtils.checkNull(dutyPoliceUsers.getTdutyUsers())){
                    stringBuffer.append(dutyPoliceUsers.getTdutyUsers());
                }
                //操作员
                if (!StringUtils.checkNull(dutyPoliceUsers.getOperatingUsers())){
                    stringBuffer.append(dutyPoliceUsers.getOperatingUsers());
                }
                //总站备勤
                if (!StringUtils.checkNull(dutyPoliceUsers.getPreparationUsers())){
                    stringBuffer.append(dutyPoliceUsers.getPreparationUsers());
                }
                //中心值班长
                if (!StringUtils.checkNull(dutyPoliceUsers.getCbigUsers())){
                    stringBuffer.append(dutyPoliceUsers.getCbigUsers());
                }
                //中心值班员
                if (!StringUtils.checkNull(dutyPoliceUsers.getCpersonUsers())){
                    stringBuffer.append(dutyPoliceUsers.getCpersonUsers());
                }


                //事务提醒
                this.ContentReminder(request,dutyPoliceUsers,stringBuffer.toString());


            }
        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    /**
     * @Author 廉立深
     * @Description 删除接口
     * @Date 16:35 2020/5/21
     * @Param [request, dutyPoliceUsers]
     * @return com.xoa.util.ToJson
     **/
    @Override
    public ToJson deleteDuty(HttpServletRequest request, String dutyIds) {
        ToJson toJson=new ToJson(1,"err");
        try {
            if (",".equals(String.valueOf(dutyIds.charAt(dutyIds.length()-1)))){
                dutyIds=dutyIds.substring(0,dutyIds.length()-1);
            }
            int i = dutyPoliceUsersMapper.deleteByPrimaryKey(dutyIds);
            if (i>0){
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }
        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    /**
     * @Author 廉立深
     * @Description 导入excel
     * @Date 10:19 2020/5/22
     * @Param [request, multipartFile]
     * @return com.xoa.util.ToJson
     **/
    @Override
    public ToJson ImportDutyPolice(HttpServletRequest request, MultipartFile multipartFile) {
        ToJson toJson=new ToJson(1,"失败");
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
        try {
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
            if (osName.toLowerCase().startsWith("win")) {
                //sb=sb.append(rb.getString("upload.win"));
                //判断路径是否是相对路径，如果是的话，加上运行的路径
                String uploadPath = rb.getString("upload.win");
                if (uploadPath.indexOf(":") == -1) {
                    //获取运行时的路径
                    String basePath = this.getClass().getClassLoader().getResource(".").getPath() + File.pathSeparator;
                    //获取截取后的路径
                    String str2 = "";
                    if (basePath.indexOf("/xoa") != -1) {
                        //获取字符串的长度
                        int length = basePath.length();
                        //返回指定字符在此字符串中第一次出现处的索引
                        int index = basePath.indexOf("/xoa");
                        //从指定位置开始到指定位置结束截取字符串
                        str2 = basePath.substring(0, index);
                    }
                    path = path.append(str2 + "/xoa");
                }
                path.append(uploadPath);
            } else {
                path = path.append(rb.getString("upload.linux"));
            }
            if (multipartFile.isEmpty()) {
                toJson.setMsg("请上传文件");
                return toJson;
            } else {
                String fileName = multipartFile.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
                    InputStream in = multipartFile.getInputStream();
                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    int lastRowNum = sheetObj.getLastRowNum();
                    for (int i=3;i <= lastRowNum; i++) {
                        Row row = sheetObj.getRow(i);

                        //要添加的对象
                        DutyPoliceUsers dutyPoliceUsers=new DutyPoliceUsers();
                        //值班日期
                        dutyPoliceUsers.setDutyDate(DateFormat.getDates(row.getCell(0).getStringCellValue()));
                        //局带班
                        dutyPoliceUsers.setBtreeUsers(usersService.fundUserIdByUserName(row.getCell(1).getStringCellValue()));
                        //局值班
                        dutyPoliceUsers.setBdutyUsers(usersService.fundUserIdByUserName(row.getCell(2).getStringCellValue()));
                        //总站带班
                        dutyPoliceUsers.setTtreeUsers(usersService.fundUserIdByUserName(row.getCell(3).getStringCellValue()));
                        //总站值班
                        dutyPoliceUsers.setTdutyUsers(usersService.fundUserIdByUserName(row.getCell(4).getStringCellValue()));
                        //操作员
                        dutyPoliceUsers.setOperatingUsers(usersService.fundUserIdByUserName(row.getCell(5).getStringCellValue()));
                        //总站备勤
                        dutyPoliceUsers.setPreparationUsers(usersService.fundUserIdByUserName(row.getCell(6).getStringCellValue()));
                        //中心值班长
                        dutyPoliceUsers.setCbigUsers(usersService.fundUserIdByUserName(row.getCell(7).getStringCellValue()));
                        //中心值班员
                        dutyPoliceUsers.setCpersonUsers(usersService.fundUserIdByUserName(row.getCell(8).getStringCellValue()));
                        //提醒内容
                        dutyPoliceUsers.setContent("新的值班信息");
                        dutyPoliceUsers.setCreateUser(users.getUserId());
                        dutyPoliceUsers.setCreateTime(new Date());
                        int i1 = dutyPoliceUsersMapper.insertSelective(dutyPoliceUsers);
                        if (i1>0){

                            StringBuffer stringBuffer=new StringBuffer();
                            //局带班
                            if (!StringUtils.checkNull(dutyPoliceUsers.getBtreeUsers())){
                                stringBuffer.append(dutyPoliceUsers.getBtreeUsers());
                            }
                            //据值班
                            if (!StringUtils.checkNull(dutyPoliceUsers.getBdutyUsers())){
                                stringBuffer.append(dutyPoliceUsers.getBdutyUsers());
                            }
                            //总站带班
                            if (!StringUtils.checkNull(dutyPoliceUsers.getTtreeUsers())){
                                stringBuffer.append(dutyPoliceUsers.getTtreeUsers());
                            }
                            //总站值班
                            if (!StringUtils.checkNull(dutyPoliceUsers.getTdutyUsers())){
                                stringBuffer.append(dutyPoliceUsers.getTdutyUsers());
                            }
                            //操作员
                            if (!StringUtils.checkNull(dutyPoliceUsers.getOperatingUsers())){
                                stringBuffer.append(dutyPoliceUsers.getOperatingUsers());
                            }
                            //总站备勤
                            if (!StringUtils.checkNull(dutyPoliceUsers.getPreparationUsers())){
                                stringBuffer.append(dutyPoliceUsers.getPreparationUsers());
                            }
                            //中心值班长
                            if (!StringUtils.checkNull(dutyPoliceUsers.getCbigUsers())){
                                stringBuffer.append(dutyPoliceUsers.getCbigUsers());
                            }
                            //中心值班员
                            if (!StringUtils.checkNull(dutyPoliceUsers.getCpersonUsers())){
                                stringBuffer.append(dutyPoliceUsers.getCpersonUsers());
                            }

                            //事务提醒
                            this.ContentReminder(request,dutyPoliceUsers,stringBuffer.toString());
                        }
                    }
                    toJson.setMsg("导入成功");
                    toJson.setFlag(0);
                }else{
                    toJson.setMsg("请上传相应格式的文件");
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    //公安局值班管理事务提醒
    @Async
    public void ContentReminder(HttpServletRequest request, final DutyPoliceUsers dutyPoliceUsers , final String todoId){
        final String sqlType = (String) request.getSession().getAttribute("loginDateSouse");
        final Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
        this.threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                ContextHolder.setConsumerType("xoa" + sqlType);
                SmsBody smsBody = new SmsBody();
                smsBody.setFromId(dutyPoliceUsers.getCreateUser());
                smsBody.setContent("公安局值班管理！主题：" + dutyPoliceUsers.getContent());
                Date date = new Date();
                long dateLong = date.getTime()/1000;
                String strDate = String.valueOf(dateLong);
                Integer dateInt = Integer.valueOf(strDate.trim());
                smsBody.setSendTime(dateInt);
                smsBody.setIsAttach("0"); //无附件
                smsBody.setRemindUrl("/dutyManagement/transactionRemind?dutyId="+dutyPoliceUsers.getDutyId());

                SysCode sysCode = new SysCode();
                sysCode.setCodeName("公安局值班管理");
                sysCode.setParentNo("SMS_REMIND");
                SysCode codeNoByNameAndParentNo = sysCodeMapper.getCodeNoByNameAndParentNo(sysCode);
                if (codeNoByNameAndParentNo != null) {
                    smsBody.setSmsType(codeNoByNameAndParentNo.getCodeNo());
                }
                String title = user.getUserName() + "：有提醒！";
                String context = "主题:"+dutyPoliceUsers.getContent();
                smsService.saveSms(smsBody, todoId, "1", "1", title, context, sqlType);

                // 企业微信提醒
                qywxService.sendMsg(Arrays.asList(todoId.split(",")),"您有新的值班提醒！",dutyPoliceUsers.getContent(),"/DutyPoliceUsers/dutyDetails?dutyId="+dutyPoliceUsers.getDutyId(),false);
            }
        });
    }
}
